package com.example.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.oss.service.OssService;
import com.example.oss.utils.ConstantYamlUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantYamlUtils.END_POINT;
        String accessKeyId = ConstantYamlUtils.KEY_ID;
        String accessKeySecret = ConstantYamlUtils.KEY_SECRET;
        String bucketName = ConstantYamlUtils.BUCKET_NAME;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //返回文件url
        String url="";

        try {
            InputStream inputStream = file.getInputStream();
            //上传初始文件名
            String fileName = file.getOriginalFilename();
            //获得随机文件名
            fileName = UUID.randomUUID().toString().replaceAll("-","")+fileName;
            //生成时间路径
            String datePath=new DateTime().toString("yyyy/MM/dd");
            fileName=datePath+fileName;
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, inputStream);
            //https://guli-edu-20220527.oss-cn-guangzhou.aliyuncs.com/avatar/svg1.jpg
            url="https://"+bucketName+"."+endpoint+"/"+fileName;

        } catch (Exception e) {
            return null;
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            return url;
        }
    }
}
